const jwt = require("jsonwebtoken");
const db = require("../models");

module.exports = async function (req, res, next) {
  const token = req.header("Authorization");

  if (!token) return res.status(403).send("Access Denied");

  try {
    const user = jwt.verify(token, process.env.TOKEN_SECRET); //获取登录用户信息
    // console.log(user);
    const department = await db.department.findOne({
      where: { id: user.department },
    }); //获取登录用户所在部门
    //权限表
    const table = {
      staff: 1,
      client: 2,
      factory: 3,
      project: 4,
      contract: 5,
      receipt: 6,
      product: 7,
      shop: 8,
      implement: 9,
      service: 10,
      problem: 11,
    };

    const reqModule = req.baseUrl.slice(1); //根据baseUrl判断用户访问的模块

    //用常量保存无需权限访问的模块

    if (
      table[reqModule] !== undefined &&
      user.level < 3 &&
      department.permission.indexOf(table[reqModule]) === -1
    ) {
      //如果该用户所在部门没有此权限并且用户不是管理员则抛出异常
      throw new Error("所属部门没有此权限");
    }

    const censorUrl = req.url.slice(1, 15); //截取审核url

    if (censorUrl === "to_be_censored") {
      if (user.level < 2) {
        throw new Error("您没有权限审核！");
      }
    }

    if (req.body.level !== undefined) {
      //仅限管理员修改用户level
      if (user.level < 3) {
        throw new Error("您没有权限修改用户操作权限！");
      }
    }
    // req.user = user;

    next();
  } catch (err) {
    res.status(401).send({ msg: err.message });
  }
};
